

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/boshi.jpeg">
  <link rel="icon" type="image/png" href="/img/boshi.jpeg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="wangpf">
  <meta name="keywords" content="">
  <title>Vue 里 computed  和 watch 的区别 - wpf的博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/foundation.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.1.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>Wangpf's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/article.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-12-20 20:48" pubdate>
      2020年12月20日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      14
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">Vue 里 computed  和 watch 的区别</h1>
            
            <div class="markdown-body" id="post-body">
              <p>​<br>​</p>
<h2 id="computed"><a href="#computed" class="headerlink" title="computed"></a>computed</h2><blockquote>
<p> 计算属性 ， computed 是用来计算出一个值，这个值在调用的时候会根据依赖的数据显示新的计算结果并自动缓存。 如果依赖不变，computed中的值就不会重新计算。 注意 ：不需要加(),</p>
</blockquote>
<h3 id="什么是计算属性，为什么要使用它"><a href="#什么是计算属性，为什么要使用它" class="headerlink" title="什么是计算属性，为什么要使用它"></a>什么是计算属性，为什么要使用它</h3><p><strong>模板内的表达式非常便利，但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护,例如：</strong></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;example&quot;</span>&gt;</span>
  &#123;&#123; message.split(&#x27;&#x27;).reverse().join(&#x27;&#x27;) &#125;&#125;
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre></div>
<p><strong>在这个地方，模板不再是简单的声明式逻辑，你必须看一段时间才能意识到，这里是想要显示变量 <code>message</code> 的翻转字符串，当你想要在模板中多次引用此处的翻转字符串时，就会更加难以处理。</strong></p>
<ul>
<li>使用 方法 methods</li>
<li>使用 计算属性 compute</li>
</ul>
<h3 id="计算属性和方法的区别"><a href="#计算属性和方法的区别" class="headerlink" title="计算属性和方法的区别"></a>计算属性和方法的区别</h3><ul>
<li>计算属性是基于他们的响应式依赖进行缓存的，只在相关响应式依赖发生改变时，才会重新求值（也就是说，计算属性会把数据进行缓存）</li>
<li>而方法不会把数据进行缓存， 所以用计算属性效率会更高点</li>
</ul>
<p><strong>所以，对于任何复杂逻辑，都应该使用计算属性</strong></p>
<ul>
<li><p>在某些情况，我们可能需要对数据进行一些转化后再显示，或者需要将多个数据结合起来进行显示</p>
<ul>
<li>比如我们有firstName和lastName两个变量，我们需要显示完整的名称。</li>
<li>但是如果多个地方都需要显示完整的名称，我们就需要写多个 </li>
</ul>
<div class="hljs"><pre><code class="hljs js"> &lt;body&gt;
  &lt;div id=<span class="hljs-string">&quot;app&quot;</span>&gt;
    &lt;h2&gt;&#123;&#123;firstName + <span class="hljs-string">&#x27; &#x27;</span> + lastName&#125;&#125;&lt;/h2&gt;
    &lt;h2&gt;&#123;&#123;firstName&#125;&#125; &#123;&#123;lastName&#125;&#125;&lt;/h2&gt;
    &lt;h2&gt;&#123;&#123;getFullName()&#125;&#125;&lt;/h2&gt;
    &lt;h2&gt;&#123;&#123;fullName&#125;&#125;&lt;/h2&gt;

  &lt;/div&gt;
&lt;/body&gt;
&lt;script src=<span class="hljs-string">&quot;../js/vue.js&quot;</span>&gt;&lt;/script&gt;
&lt;script&gt;
  <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Vue(&#123;
    el: <span class="hljs-string">&#x27;#app&#x27;</span>,
    data: &#123;
      firstName: <span class="hljs-string">&#x27;Lron&#x27;</span>,
      lastName: <span class="hljs-string">&#x27;Man&#x27;</span>
    &#125;,
    <span class="hljs-comment">// 推荐使用计算属性来操作，因为它会将这些数据进行缓存， 无论打印多少次，它只会调用一次</span>
    computed: &#123;
    <span class="hljs-comment">//  计算属性   注意 : 计算的是 属性, </span>
    <span class="hljs-comment">// 所以这里面的属性 看成一个 对象(用名词形式来表达), 调用时候不用加小括号</span>
      fullName: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">&#x27; &#x27;</span> + <span class="hljs-built_in">this</span>.lastName

      &#125;
    &#125;,
    methods: &#123;
      <span class="hljs-comment">//  不会缓存， 所以有多少次就调用多少次，  没有 computed 划算</span>
      getFullName: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">&#x27; &#x27;</span> + <span class="hljs-built_in">this</span>.lastName
      &#125;
    &#125;
  &#125;)
&lt;/script&gt;</code></pre></div>

</li>
</ul>
<h2 id="watch"><a href="#watch" class="headerlink" title="watch"></a>watch</h2><p>参考文档：<a target="_blank" rel="noopener" href="https://cn.vuejs.org/v2/api/#watch">vue官方文档：watch</a></p>
<blockquote>
<p>监听， 如果某个属性依赖变化了就执行回调。  它有俩个属性 1. immediate  表示数据是否在第一次渲染的时候立即执行该函数。    2. deep , 如果我们监听一个对象（不包括数组），是否要看对象里面的属性的变化。</p>
</blockquote>
<h3 id="什么是watch-为什么要使用它"><a href="#什么是watch-为什么要使用它" class="headerlink" title="什么是watch 为什么要使用它"></a>什么是watch 为什么要使用它</h3><p>watch监听的<strong>数据</strong>可以是一个 <strong>字符串、函数、数组、对象</strong></p>
<p>一个对象，键是需要观察的表达式（<strong>data内的数据</strong>），值是对应回调函数。值也可以是方法名，或者包含选项的对象。</p>
<p>当数据发生改变时，会执行一个回调，它有俩个参数， newVal 和 oldVal</p>
<p>wtach有俩个属性：</p>
<ul>
<li>immediate 是否在第一次渲染时执行这个函数，会在监听开始之后就立即本调用。</li>
<li>deep 是否要看这个对象里面的属性变化。</li>
</ul>
<p><strong>this.$watch 和 watch 用法一致，只不过写法有些不同，这里不详细说明</strong></p>
<p>案例：</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  data: &#123;
    n: <span class="hljs-number">0</span>,
    obj: &#123;
      a: <span class="hljs-string">&quot;a&quot;</span>
    &#125;
  &#125;,
  template: <span class="hljs-string">`</span>
<span class="hljs-string">    &lt;div&gt;</span>
<span class="hljs-string">      &lt;button @click=&quot;n += 1&quot;&gt;n+1&lt;/button&gt;</span>
<span class="hljs-string">      &lt;button @click=&quot;obj.a += &#x27;hi&#x27;&quot;&gt;obj.a + &#x27;hi&#x27;&lt;/button&gt;</span>
<span class="hljs-string">      &lt;button @click=&quot;obj = &#123;a:&#x27;a&#x27;&#125;&quot;&gt;obj = 新对象&lt;/button&gt;</span>
<span class="hljs-string">    &lt;/div&gt;</span>
<span class="hljs-string">  `</span>,
  watch: &#123;
    n() &#123;
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;n 变了&quot;</span>);
    &#125;,
    obj:&#123;
      handler: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">val, oldVal</span>) </span>&#123; 
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;obj 变了&quot;</span>)
    &#125;,
      deep: <span class="hljs-literal">true</span> <span class="hljs-comment">// 该属性设定在任何被侦听的对象的 property 改变时都要执行 handler 的回调，不论其被嵌套多深</span>
    &#125;,
    <span class="hljs-string">&quot;obj.a&quot;</span>:&#123;
      handler: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">val, oldVal</span>) </span>&#123; 
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;obj.a 变了&quot;</span>)
    &#125;,
      immediate: <span class="hljs-literal">true</span> <span class="hljs-comment">// 该属性设定该回调将会在侦听开始之后被立即调用</span>
    &#125;
  &#125;
&#125;).$mount(<span class="hljs-string">&quot;#app&quot;</span>);</code></pre></div>

<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><ol>
<li>如果一个数据需要经过复杂计算就用 computed</li>
<li>如果一个数据需要在发生变化时做一些操作就用 watch</li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                <div class="post-meta mr-3">
                  <i class="iconfont icon-category"></i>
                  
                  <a class="hover-with-bg" href="/categories/vue/">vue</a>
                  
                </div>
                
                
                <div class="post-meta">
                  <i class="iconfont icon-tags"></i>
                  
                  <a class="hover-with-bg" href="/tags/vue/">vue</a>
                  
                </div>
                
              </div>
              
              
              <div class="post-prevnext row">
                <article class="post-prev col-6">
                  
                  
                  <a href="/2020/12/21/37.vue%E4%BF%AE%E9%A5%B0%E7%AC%A6/">
                    <i class="iconfont icon-arrowleft"></i>
                    <span class="hidden-mobile">Vu sync修饰符</span>
                    <span class="visible-mobile">上一篇</span>
                  </a>
                  
                </article>
                <article class="post-next col-6">
                  
                  
                  <a href="/2020/12/20/35-Vue%E4%BF%A9%E4%B8%AA%E7%89%88%E6%9C%AC/">
                    <span class="hidden-mobile">vue俩个版本：runtime-compiler和 runtime-only 的区别</span>
                    <span class="visible-mobile">下一篇</span>
                    <i class="iconfont icon-arrowright"></i>
                  </a>
                  
                </article>
              </div>
              
            </div>

            
            <!-- Comments -->
            <article class="comments" id="comments">
              
              
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "hjxsDRXYScicliqD8I8JqoTu-gzGzoHsz",
          app_key: "qUcAEReEqeEVp5wwXJ41uCCp",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: true,
          recordIP: false,
          serverURLs: "",
        });
      });
    }
    waitElementVisible('vcomments', loadValine);
  </script>
  <noscript>Please enable JavaScript to view the <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


            </article>
            
          </article>
        </div>
      </div>
    </div>
    
    <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
      <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

    </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Vue 里 computed  和 watch 的区别&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "always",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  











  

  

  

  

  

  





</body>
</html>
